<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class user extends MY_Controller {
	function __construct(){
		parent::__construct();
	}

	function index(){;
		$is_loggedin = $this->session->userdata("is_loggedin");
		$usr_data = $this->session->userdata("user_data");

		if(empty($is_loggedin)){
			redirect(base_url("user/login"),"refresh");
		}else{
			$id = $this->session->userdata("user_id");
			$this->_assign('id',$id);
			if($usr_data['group'] == 2){
				redirect(base_url("admin"),"refresh");
			}
			PageUtil::addVar("title","Truck.co.th ตลาดซื้อขายรถบรรทุกและเครื่องจักรกลหนักทุกชนิด");
			$this->_fetch('index');
		}
	}

	function login(){
		$is_loggedin = $this->session->userdata("is_loggedin");
		if($is_loggedin){
			redirect(base_url("user"),"refresh");
		}else{
			PageUtil::addVar("title","เข้าสู่ระบบ - Truck.co.th ตลาดซื้อขายรถบรรทุกและเครื่องจักรกลหนักทุกชนิด");
			$this->_fetch("login");
		}
	}

	function checklogin(){
		$this->load->model("user_model","userModel");
		$_post = $this->input->post();

		//Check input
		if(empty($_post["username"])){
			$this->session->set_flashdata('error_message', "กรุณากรอก Username และลองอีกครั้ง!");
			redirect(base_url("user/login"));	
		}
		if(empty($_post["password"])){
			$this->session->set_flashdata('error_message', "กรุณากรอก Password และลองอีกครั้ง!");
			redirect(base_url("user/login"));	
		}

		//Check username and password are match
		$_query["username"] = $_post["username"];
		$_query["password"] = md5($_post["password"]);
		$result = $this->userModel->get($_query);
		if($result == FALSE){
			$this->session->set_flashdata('error_message', "Username และ Password ไม่ตรงกัน โปรดลองอีกครั้ง!");
			redirect(base_url("user/login"));			
		}else{
			//Update LastActive
			$whereAdd["id"] = $result[0]['id'];
			$whereAdd["lastactive"] = date( 'Y-m-d H:i:s');
			if(!$this->userModel->add($whereAdd)){
				log_message("error","Can't update LastActive at ".__FILE__.":".__LINE__);
			}
			//Update User IP Address
			$this->load->model("user_ip_model","userIpModel");
			$whereAddUserIP["ip"] = $this->input->ip_address();
			$whereAddUserIP["usr_id"] = $result[0]['id'];
			$whereAddUserIP["time"] = date('Y-m-d H:i:s');
			$whereAddUserIP["action"] = "login";
			if(!$this->userIpModel->add($whereAddUserIP)){
				log_message("error","Can't add user ip adress at ".__FILE__.":".__LINE__);
			}

			unset($result[0]["password"]);
			unset($result[0]["lastactive"]);
			unset($result[0]["registered"]);
			$this->session->set_userdata("is_loggedin",TRUE);
			$this->session->set_userdata("user_data",$result[0]);
			$this->session->set_userdata("user_id",$result[0]['id']);
			redirect(base_url("user"));
		}
	}

	function register(){
		$_post = $this->input->post();

		if(empty($_post["submitbtn"])){
			if(CIUser::getAuthInfo()){
				redirect(base_url("user"),"refresh");
			}
			PageUtil::addVar("title","สมัครสมาชิก - Truck.co.th ตลาดซื้อขายรถบรรทุกและเครื่องจักรกลหนักทุกชนิด");
			$this->_fetch("register");
		}else{
			$is_loggedin = $this->session->userdata("is_loggedin");
			$usr_data = $this->session->userdata("user_data");

			$this->load->model("user_model","userModel");

			if(empty($_post["group"])){
				$_post["group"] = 1;
			}

			if(!empty($_post["password"]) AND $_post["password"] != ""){
				$emailpassword = $_post["password"];
				$_post["password"] = md5($_post["password"]);
			}else{
				unset($_post["password"]);
			}
			$_post["registered"] = date( 'Y-m-d H:i:s');
			$_post["lastactive"] = date( 'Y-m-d H:i:s');
			$result = $this->userModel->add($_post);
			if(!$result){
				log_message("error","Can't register at ".__FILE__.":".__LINE__);
			}
			//Update User IP Address
			$this->load->model("user_ip_model","userIpModel");
			$whereAddUserIP["ip"] = $this->input->ip_address();
			$whereAddUserIP["usr_id"] = $result;
			$whereAddUserIP["time"] = date( 'Y-m-d H:i:s');
			$whereAddUserIP["action"] = "register";
			if(!$this->userIpModel->add($whereAddUserIP)){
				log_message("error","Can't add user ip adress at ".__FILE__.":".__LINE__);
			}
			//Send an E-Mail.
			if(empty($_post["id"])){
				$email = $_post["email"];
				$this->load->library('email');
				$this->email->from('no-reply@trock.co.th', 'Truck');
				$this->email->to($email);
				$this->email->subject('คุณได้เป็นสมาชิกของ www.Truck.co.th');
				$this->email->message('Username ของคุณคือ '.$_post["username"]."\nPassword ของคุณคือ ".$emailpassword);
				$emailsent = $this->email->send();
			}
			if($usr_data['group'] == 2){
				redirect(base_url("admin"),"refresh");
			}else{
				redirect("user");
			}
		}
	}

	function ajax_checkuser(){
		if(!IS_AJAX){
			show_404();
		}
		$data = $this->input->get();

		$this->load->model("user_model","userModel");
		$where['where']['username']=$data['username'];
		$checkusername=$this->userModel->get($where);
		if($checkusername==TRUE){
			$data['responseText'] = "false";
			echo $data['responseText'];exit;
		}else{
			$data['responseText'] = "true";
			echo $data['responseText'];exit;
		}
	}

	function admin_list(){
		$this->load->model("user_model","userModel");
		$datauser = $this->userModel->get();
		$this->_assign('datauser',$datauser);
		$this->_fetch("admin_list");
	}

	function edituser($id = NULL){
		$usr_id = $this->session->userdata("user_id");
		$usr_data = $this->session->userdata("user_data");		
		$this->_assign('user_data',$usr_data);
		$_post = $this->input->post();
		if(!empty($_post["submitbtn"])){
			self::register();
		}

		$this->load->model('group_model','groupModel');
		$group = $this->groupModel->get();
		$this->_assign('groups',$group);
		if(($id != NULL) AND ($usr_data['group'] == 2) ){
			$where["where"]["id"] = $id;
			$result = $this->userModel->get($id);
			$this->_assign("data",$result);
			$this->_fetch("admin_edituser");
		}else if(!empty($usr_id)){
			$where["where"]["id"] = $usr_id;
			$result = $this->userModel->get($where);
			$this->_assign("data",$result);
			$this->_fetch("admin_edituser");
		}else{
			show_404();
		}
	}

	function admin_delete($id="",$status=""){

		$usr_data = $this->session->userdata("user_data");

		$this->load->model('user_model','userModel');

		if(!empty($usr_data) AND $usr_data['group']==2){

    if($status == 0){

			$resultuser = $this->userModel->get($id);
			$delmember['id'] = $id;
			$delmember['status'] = 1;  //staus = 1 invisible
			$this->userModel->add($delmember);
			$this->_assign('banstatus',$resultuser[0]['status']);

		}elseif($status == 1){

			$delmember1['id'] = $id;
			$delmember1['status'] = 0;  //staus = 0 Unlock
			$this->userModel->add($delmember1);


		}

			redirect('user/admin_list');

		}
	}



	function logout(){
		$this->session->set_userdata("is_loggedin",FALSE);
		$this->session->set_userdata("user_data",FALSE);
		$this->session->set_userdata("user_id",FALSE);
		redirect(base_url(),"refresh");
	}

}